<?php

//include("config.php");

require_once ("Constants.php");
require_once ("Util.php");

/**
 * Description of Validation
 *
 * @author riemerb
 */
class Validation {

    private $errorArray;
    private $errorCount = 0;
    private $db;

    function __construct() {
        // Mit Datenbank verbinden
        $this->db = mysqli_connect(Constants::DB_HOST, Constants::DB_BENUTZER, Constants::DB_PASSWORT, Constants::DB_NAME);
        mysqli_set_charset($this->db, "utf8");
    }

    function validatePassword($password, $password2) {
        if (strcmp($password, $password2) != 0) {
            $this->addError("Die beiden Passwörter stimmen nicht überein.");
        }
    }

    function validateDateAfter($from, $to, $message) {
        $time_from = strtotime($from);
        $time_to = strtotime($to);
        if ($time_from > $time_to){
             $this->addError($message);
        }
    }

    function validateRequiredBoolean($value, $message) {
        if (isset($_POST[$value])) {
            $string = htmlentities(trim($_POST[$value]),ENT_COMPAT,"UTF-8");
            if (empty($string)) {
                $this->addError($message);
                return "";
            }
            if (strcmp($string, 'TRUE') == 0) {
                return TRUE;
            } else {
                return FALSE;
            }
        } else {
            $this->addError($message);
            return "";
        } 
    }
    
    function validateRequiredString($value, $message) {
        if (isset($_POST[$value])) {
            //$string = htmlentities(mysqli_real_escape_string($this->db, trim($_POST[$value])));
            $string = htmlentities(trim($_POST[$value]),ENT_COMPAT,"UTF-8");
            //$string = str_replace("\\r\\n","<br>", htmlentities(mysqli_real_escape_string($this->db, trim($_POST[$value]))));
            //$string = trim($_POST[$value]);            
            if (empty($string)) {
                $this->addError($message);
                return "";
            }
            return $string;
        } else {
            if (empty($string)) {
                $this->addError($message);
                return "";
            }
        }
    }

    function validateString($value) {
        //return mysqli_real_escape_string($this->db, trim($_POST[$value]));
        //return $string = str_replace("\\r\\n","<br>", htmlentities(mysqli_real_escape_string($this->db, trim($_POST[$value]))));
        return $string = htmlentities(trim($_POST[$value]),ENT_COMPAT,"UTF-8");
        //return trim($_POST[$value]);
    }

    /**
     *
     * @param type $email
     * @return boolean 
     */
    function isEmail($email) {

        //email is not case sensitive make it lower case
        $email = strtolower($email);

        //check if email seems valid
        if (preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $email)) {
            return $email;
        }

        return false;
    }

    /**
     *
     * @param type $phone
     * @param type $ext
     * @return boolean 
     */
    function isPhone($phone, $ext = false) {

        //remove everything but numbers
        $numbers = preg_replace("%[^0-9]%", "", $phone);

        //how many numbers are supplied
        $length = strlen($numbers);

        if ($length == 10 || $length == 7) { //Everything is find and dandy
            $cleanPhone = $numbers;

            if ($ext) {
                $clean['phone'] = $cleanPhone;
                return $clean;
            } else {
                return $cleanPhone;
            }
        } elseif ($length > 10) { //must be extension
            //checks if first number is 1 (this may be a bug for you)
            if (substr($numbers, 0, 1) == 1) {
                $clean['phone'] = substr($numbers, 0, 11);
                $clean['extension'] = substr($numbers, 11);
            } else {
                $clean['phone'] = substr($numbers, 0, 10);
                $clean['extension'] = substr($numbers, 10);
            }

            if (!$ext) { //return string
                if (!empty($clean['extension'])) {
                    $clean = implode("x", $clean);
                } else {
                    $clean = $clean['phone'];
                }

                return $clean;
            } else { //return array
                return $clean;
            }
        }

        return false;
    }

    /**
     *
     * @param type $postal
     * @return boolean 
     */
    function isPostalCode($postal) {
        $regex = "/^([a-ceghj-npr-tv-z]){1}[0-9]{1}[a-ceghj-npr-tv-z]{1}[0-9]{1}[a-ceghj-npr-tv-z]{1}[0-9]{1}$/i";

        //remove spaces
        $postal = str_replace(' ', '', $postal);

        if (preg_match($regex, $postal)) {
            return $postal;
        } else {
            return false;
        }
    }

    /**
     *
     * @param type $zip
     * @return boolean 
     */
    function isZipCode($zip, $message) {
        //remove everything but numbers
        $numbers = preg_replace("[^0-9]", "", $zip);

        //how many numbers are supplied
        $length = strlen($numbers);

        if ($length != 4) {
            $this->addError($message);
        } else {
            return $numbers;
        }
    }

        /**
     *
     * @param type $age
     * @return the age 
     */
    function validateAge($age, $message) {
         if (isset($_POST[$age])) {
             $string = htmlentities(trim($_POST[$age]),ENT_COMPAT,"UTF-8");
         
            //remove everything but numbers
            $asNumber = preg_replace("[^0-9]", "", $string);

            //how many numbers are supplied
            $length = strlen($asNumber);

            if ($length != 4) {
                $this->addError('Das Geburtsjahr hat kein vierstelliges Format!');
                return $string;
            } else {
                $year = intval($asNumber);
                if ($year < 1900 || $year > date("Y")){
                    $this->addError("Das Geburtsjahr ist nicht realistisch!");
                    return $year;
                } else {
                    return $year;
                }
            }
        } else {
            $this->addError($message);
        }
    }

    /**
     *
     * @param type $zip
     * @return boolean 
     */
    function isKilometerEntry($value, $message) {
        //remove everything but numbers
        $value = preg_replace("/,/", ".", $value);
        //remove everything but numbers
//        if (preg_match('/^\d{1,6}[/.]?[\d]?', $value) == 0)
        if (preg_match('/^\d{1,6}\.?\d?$/', $value) == 0)
        {
            $this->addError($message);
            return $value;
        }
        return $value;
    }
    
    function valid_email($email, $message) {
        if ( filter_var($email, FILTER_VALIDATE_EMAIL) ) {
            return true;
        } else {
            $this->addError($message);
            return false;
        }
    }

    /**
     *
     * @param type $zip
     * @return boolean 
     */
    function isDateFormat($value, $message) {
        if (preg_match('/^\d{2}\.\d{2}\.\d{4}$/', $value) == 0)
        {
            $this->addError($message);
            return false;
        }
    }
    
    public function isError() {
        if ($this->errorCount > 0) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    public function compairString($value1, $value2, $varName1, $varName2) {
        if (strcmp($value1, $value2) != 0){
            $this->addError('Die Werte '.$varName1.' und '.$varName2.' sollten gleich sein.');
        }
        return $this->errorArray;
    }

    
    public function getErrorMessage() {
        return $this->errorArray;
    }

    public function addError($message) {
        $this->errorArray[$this->errorCount] = $message;
        $this->errorCount = $this->errorCount + 1;
    }
    
    public function dateNotOlderThan($date, $interval, $message){
        if (Util::isOlderThan($date, $interval)){
            $this->addError($message);
        }
    }

    public function isDateInFuture($date, $message){
        if (Util::isInFuture($date)){
            $this->addError($message);
        }
    }
    
    /**
     * Valid date. 
     * 
     * @param type $value
     * @param type $message
     */
    function validateRequiredSaisonSelection($value, $message) {
        if (isset($_POST[$value])) {
            $unSaveValue = $_POST[$value];
            $stringSaison = htmlentities(trim($unSaveValue),ENT_COMPAT,"UTF-8");
            $dateArray = explode("-", $stringSaison);
            $stringFrom = trim($dateArray[0]);
            $stringTo = trim($dateArray[1]);
            
            if (! $this->isDateFormat($stringFrom, "Kein gültiges Saison Datum.")) {
                $time_from = strtotime(trim($dateArray[0]));
            }
            if (! $this->isDateFormat($stringTo, "Kein gültiges Saison Datum.")) {
                $time_to = strtotime(trim($dateArray[1]));
            }
            return new Saison(0, $stringFrom, $stringTo);
        }
    }
}
